package thing

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"iot-base/auth/api/logic"
	Log "iot-base/auth/logger"
	types2 "iot-base/auth/types"
	"iot-base/auth/utils"
	"iot-base/common/cache"
	"iot-base/common/params"
)

func QueryHis(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	uid := c.GetInt64("uid")
	resp := types2.NewResult(c)
	var req types2.ReqQueryHis
	if err := c.ShouldBind(&req); err != nil {
		fmt.Println(err)
		Log.Log.Errorf("[%s] [%v] err:=%v", requestId, uid, err)
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	hisLogic := logic.NewHisLogic()
	total, err := hisLogic.QueryHisTotal(req.StationId, req.Classify, req.StartTime, req.EndTime)
	if err != nil {
		Log.Log.Errorf("[%s] [%v] err:=%v", requestId, uid, err)
		resp.ErrorCode(types2.DBError, "")
		return
	}
	result, err := hisLogic.QueryHis(req.StationId, req.Page, req.Size, req.Classify, req.StartTime, req.EndTime)
	if err != nil {
		Log.Log.Errorf("[%s] [%v] err:=%v", requestId, uid, err)
		resp.ErrorCode(types2.DBError, "")
		return
	}
	resp.Success(gin.H{"list": result, "total": total})
}

// ExportHis 导出
func ExportHis(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	uid := c.GetInt64("uid")
	resp := types2.NewResult(c)
	var req types2.ReqExcelHis
	if err := c.ShouldBind(&req); err != nil {
		Log.Log.Errorf("[%s] [%v] err:=%v", requestId, uid, err)
		resp.ErrorCode(types2.ParamsError, err.Error())
		return
	}
	excelData, err := logic.NewHisLogic().ExcelHis(req.StationId, req.Classify, req.StartTime, req.EndTime)
	if err != nil {
		Log.Log.Errorf("[%s] [%v] err:=%v", requestId, uid, err)
		resp.ErrorCode(types2.ParamsError, err.Error())
		return
	}
	title := []interface{}{"时间", "PM10", "PM2.5", "SO2", "NO", "NO2", "NOX", "O3", "CO"}
	err = utils.ExportExcelBySlice(c, title, excelData, "his_data", "sheet1")
	if err != nil {
		Log.Log.Errorf("[%s] [%v] err:=%v", requestId, uid, err)
		resp.ErrorCode(types2.ParamsError, err.Error())
		return
	}
	return
}

func QueryData(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	uid := c.GetInt64("uid")
	resp := types2.NewResult(c)
	var req types2.ReqThingData
	if err := c.ShouldBind(&req); err != nil {
		fmt.Println(err)
		Log.Log.Errorf("[%s] [%v] err:=%v", requestId, uid, err)
		resp.ErrorCode(types2.ParamsError, err.Error())
		return
	}
	var datas []*params.ValueInRedis
	var err error
	if req.Type == "hour" {
		datas, err = cache.GetIntegralHourDatas(req.ThingId, req.Field, "", 0)
	} else {
		datas, err = cache.GetLastValues(req.ThingId, req.Field, "", 0)
	}
	if err != nil {
		resp.ErrorCode(types2.Fail, err.Error())
		return
	}
	resp.Success(datas)
	return
}
